import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'secure_storage.dart';

void main() {
  runApp(const AppLoader());
}

class AppLoader extends StatefulWidget {
  const AppLoader({super.key});

  @override
  State<AppLoader> createState() => _AppLoaderState();
}

class _AppLoaderState extends State<AppLoader> {
  late Future _initFuture;

  @override
  void initState() {
    super.initState();
    _initFuture = _initializeApp();
  }

  Future<void> _initializeApp() async {
    WidgetsFlutterBinding.ensureInitialized();
    try {
      await Get.putAsync(() => SecureStorageService().init());
    } catch (e) {
      debugPrint("初始化失败: $e");
      Get.offAll(const SafeModeApp());
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _initFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return const SafeModeApp();
          }
          return const MyApp();
        }
        return const MaterialApp(
          home: Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          ),
        );
      },
    );
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '安全存储演示',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const SecureStorageDemo(),
    );
  }
}

class SecureStorageDemo extends StatefulWidget {
  const SecureStorageDemo({super.key});

  @override
  _SecureStorageDemoState createState() => _SecureStorageDemoState();
}

class _SecureStorageDemoState extends State<SecureStorageDemo> {
  final TextEditingController _keyController = TextEditingController();
  final TextEditingController _valueController = TextEditingController();
  String _result = '';
  bool _isLoading = false;

  Future<void> _writeData() async {
    if (_keyController.text.isEmpty || _valueController.text.isEmpty) {
      setState(() => _result = '键和值不能为空!');
      return;
    }

    setState(() => _isLoading = true);
    try {
      await SecureStorageService.instance.write(
        _keyController.text,
        _valueController.text,
      );
      setState(() => _result = '数据保存成功!');
    } catch (e) {
      setState(() => _result = '保存失败: ${e.toString()}');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  Future<void> _readData() async {
    if (_keyController.text.isEmpty) {
      setState(() => _result = '键不能为空!');
      return;
    }

    setState(() => _isLoading = true);
    try {
      final value = await SecureStorageService.instance.read(_keyController.text);
      setState(() => _result = value ?? '未找到对应数据');
    } catch (e) {
      setState(() => _result = '读取失败: ${e.toString()}');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('安全存储演示')),
      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                TextField(
                  controller: _keyController,
                  decoration: const InputDecoration(
                    labelText: '键',
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 10),
                TextField(
                  controller: _valueController,
                  decoration: const InputDecoration(
                    labelText: '值',
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                      onPressed: _isLoading ? null : _writeData,
                      child: const Text('写入'),
                    ),
                    ElevatedButton(
                      onPressed: _isLoading ? null : _readData,
                      child: const Text('读出'),
                    ),
                  ],
                ),
                const SizedBox(height: 20),
                const Text('结果:', style: TextStyle(fontSize: 18)),
                const SizedBox(height: 10),
                Expanded(
                  child: SingleChildScrollView(
                    child: Text(_result, style: const TextStyle(fontSize: 16)),
                  ),
                ),
              ],
            ),
          ),
          if (_isLoading)
            const Center(child: CircularProgressIndicator()),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _keyController.dispose();
    _valueController.dispose();
    super.dispose();
  }
}

class SafeModeApp extends StatelessWidget {
  const SafeModeApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.error_outline, size: 60, color: Colors.red),
              const SizedBox(height: 20),
              const Text('安全存储初始化失败', style: TextStyle(fontSize: 18)),
              const SizedBox(height: 30),
              ElevatedButton(
                onPressed: () => Get.offAll(const MyApp()),
                child: const Text('重新尝试'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}